import os
import tempfile
from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip
from moviepy.video.tools.subtitles import SubtitlesClip
import pysrt


class SubtitleBurner:
    """字幕烧录器"""
    
    def __init__(self):
        self.supported_formats = ['.mp4', '.avi', '.mov', '.mkv', '.wmv', '.flv']
        
    def burn_subtitles_to_video(self, video_path, subtitles, output_path, 
                                font_size=24, font_color='white', 
                                outline_color='black', outline_width=2):
        """
        将字幕烧录到视频中
        
        Args:
            video_path: 输入视频路径
            subtitles: 字幕列表，格式为 [{"start": QTime, "end": QTime, "text": str}, ...]
            output_path: 输出视频路径
            font_size: 字体大小
            font_color: 字体颜色
            outline_color: 描边颜色
            outline_width: 描边宽度
        """
        try:
            # 加载视频
            video = VideoFileClip(video_path)
            
            # 转换字幕格式
            subtitle_clips = self._create_subtitle_clips(
                subtitles, video.duration, font_size, font_color, 
                outline_color, outline_width
            )
            
            # 合成视频和字幕
            final_video = CompositeVideoClip([video] + subtitle_clips)
            
            # 导出视频
            final_video.write_videofile(
                output_path,
                codec='libx264',
                audio_codec='aac',
                temp_audiofile='temp-audio.m4a',
                remove_temp=True
            )
            
            # 清理资源
            video.close()
            final_video.close()
            
            return True, "字幕烧录成功"
            
        except Exception as e:
            return False, f"字幕烧录失败: {str(e)}"
            
    def _create_subtitle_clips(self, subtitles, video_duration, font_size, 
                               font_color, outline_color, outline_width):
        """创建字幕片段"""
        subtitle_clips = []
        
        for subtitle in subtitles:
            # 转换时间格式
            start_time = self._qtime_to_seconds(subtitle["start"])
            end_time = self._qtime_to_seconds(subtitle["end"])
            
            # 确保时间在视频范围内
            if start_time >= video_duration:
                continue
            if end_time > video_duration:
                end_time = video_duration
                
            # 创建字幕文本片段
            text_clip = TextClip(
                subtitle["text"],
                fontsize=font_size,
                color=font_color,
                stroke_color=outline_color,
                stroke_width=outline_width,
                font='Arial-Bold',
                method='caption',
                size=(video.w, None)  # 宽度适应视频，高度自适应
            )
            
            # 设置字幕位置（底部居中）
            text_clip = text_clip.set_position(('center', 'bottom'))
            
            # 设置时间
            text_clip = text_clip.set_start(start_time).set_end(end_time)
            
            subtitle_clips.append(text_clip)
            
        return subtitle_clips
        
    def _qtime_to_seconds(self, qtime):
        """将QTime转换为秒数"""
        return qtime.hour() * 3600 + qtime.minute() * 60 + qtime.second() + qtime.msec() / 1000.0
        
    def create_srt_file(self, subtitles, output_path):
        """创建SRT字幕文件"""
        try:
            with open(output_path, 'w', encoding='utf-8') as f:
                for i, subtitle in enumerate(subtitles):
                    # 序号
                    f.write(f"{i + 1}\n")
                    
                    # 时间
                    start_str = subtitle["start"].toString("HH:mm:ss,zzz").replace(".", ",")
                    end_str = subtitle["end"].toString("HH:mm:ss,zzz").replace(".", ",")
                    f.write(f"{start_str} --> {end_str}\n")
                    
                    # 内容
                    f.write(f"{subtitle['text']}\n\n")
                    
            return True, "SRT文件创建成功"
        except Exception as e:
            return False, f"SRT文件创建失败: {str(e)}"
            
    def extract_subtitles_from_video(self, video_path):
        """从视频中提取字幕（如果存在）"""
        # 这里可以实现从视频中提取硬编码字幕的功能
        # 目前返回空列表
        return []
        
    def get_video_info(self, video_path):
        """获取视频信息"""
        try:
            video = VideoFileClip(video_path)
            info = {
                'duration': video.duration,
                'fps': video.fps,
                'size': video.size,
                'width': video.w,
                'height': video.h
            }
            video.close()
            return True, info
        except Exception as e:
            return False, f"获取视频信息失败: {str(e)}"
            
    def validate_subtitles(self, subtitles, video_duration):
        """验证字幕时间是否有效"""
        errors = []
        
        for i, subtitle in enumerate(subtitles):
            start_time = self._qtime_to_seconds(subtitle["start"])
            end_time = self._qtime_to_seconds(subtitle["end"])
            
            # 检查时间顺序
            if start_time >= end_time:
                errors.append(f"字幕 {i+1}: 开始时间不能晚于或等于结束时间")
                
            # 检查时间范围
            if start_time < 0:
                errors.append(f"字幕 {i+1}: 开始时间不能为负数")
                
            if end_time > video_duration:
                errors.append(f"字幕 {i+1}: 结束时间超出视频长度")
                
            # 检查内容
            if not subtitle["text"].strip():
                errors.append(f"字幕 {i+1}: 内容不能为空")
                
        return errors 